package com.thprojects.myphotomemories.view;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.facebook.android.FacebookError;
import com.facebook.android.R;
import com.thprojects.myphotomemories.controller.BaseRequestListener;
import com.thprojects.myphotomemories.controller.FSController;
import com.thprojects.myphotomemories.controller.FacebookController;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.model.Photo;

import exception.PhotoSourceNotFoundException;
import exception.SDNotReadyException;


public class ShareFbView extends Activity {

    FacebookController mFacebookController;
    Photo mPhoto;
    Button mPublish, mCancel;
    EditText mComment;
    ImageView mPreview;
    FSController mFSController;
    ProgressDialog mPDialog;
    Handler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_fb_view);
        
        Intent i = getIntent();
        mPhoto = (Photo) i.getParcelableExtra("photo");
        
        mFacebookController = new FacebookController("468759116484000", this, new String[]{"publish_stream"});
        mFSController = FSController.getFSController(this);
        mHandler = new Handler();
        
        mPublish = (Button)findViewById(R.id.fb_publish);
        mCancel = (Button)findViewById(R.id.fb_cancel);
        mComment = (EditText)findViewById(R.id.fb_comment);
        mPreview = (ImageView)findViewById(R.id.fb_photo);
        
        mPublish.setOnClickListener(new OnClickListener() {		
			public void onClick(View v) {
				if (!isOnline()){
					//show error
					GuiController.showError(ShareFbView.this, "You must be connected to Internet to publish a photo");
					return;
				}
				mPDialog = ProgressDialog.show(ShareFbView.this, "", "Uploading image. Please wait...", true);
				mFacebookController.postPhotoOnWall(
					mComment.getText().toString(),
					BitmapFactory.decodeFile(mPhoto.getPath()),
					new PhotoUploadListener()
				);
			}
		});
        
        mCancel.setOnClickListener(new OnClickListener() {		
			public void onClick(View v) {
				finish();
			}
		});
        
        Display d = getWindowManager().getDefaultDisplay();
        try {
			Bitmap img = mFSController.decodeSampledBitmap(mPhoto.getPath(), d.getWidth(), d.getWidth());
			mPreview.setImageBitmap(img);
		} 
        catch (PhotoSourceNotFoundException e) {
		} 
        catch (SDNotReadyException e) {
		}
    }
    
    private boolean isOnline() {
    	ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    	if (cm==null || cm.getActiveNetworkInfo() == null) return false;
    	return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }
    
    private void showPostDialog(boolean b){
    	String msg = b ? "Your photo has been posted" : "Can't post your photo right now. Please try again"; 
		AlertDialog.Builder builder = new AlertDialog.Builder(ShareFbView.this);
		builder.setMessage(msg)
		       .setCancelable(false)
		       .setTitle("Post on Facebook")
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   ShareFbView.this.finish();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
    }
    
	
	private class PhotoUploadListener extends BaseRequestListener {

        
        public void onComplete(final String response, final Object state) {
        	mPDialog.dismiss();
            mHandler.post(new Runnable() {   
                public void run() {
                    showPostDialog(true);
                }
            });
        }

		/* (non-Javadoc)
		 * @see com.thprojects.myphotomemories.controller.BaseRequestListener#onFacebookError(com.facebook.android.FacebookError, java.lang.Object)
		 */
		@Override
		public void onFacebookError(FacebookError e, Object state) {
			mPDialog.dismiss();
            mHandler.post(new Runnable() {   
                public void run() {
                    showPostDialog(false);
                }
            });
		}
 
    }
}



